<?php

namespace app\command\controller;

use app\common\func\Lib;
use app\common\func\Libs;
use app\common\func\Tools;
use app\common\func\Transaction;
use app\common\model\EquipFigure;
use app\common\model\FlowInfo;
use app\common\model\FlowSft;
use app\common\model\Policy;
use app\common\model\StandardMoney;
use app\common\model\StandardRecord;
use app\common\model\transaction\Xyf;
use fast\Http;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;

//盛付通
class Sft extends Controller
{
    protected $baseUrl = "./trade_log/sft/";

    //订单通知
    public function index()
    {
        $data = request()->param();
//        file_put_contents($this->baseUrl."test_data.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
//        $data = '{"mercId":"800220000000000","agtMercId2_1":"S23102100091302","agtMercId2_2":"S23102100091406","cashAmt":"210","sign":"dj1fjopIL1hzC39HscVftg6oNyumqrxYFecmazX91RhmxYPljfCl8tAVYncoXwhs6uvoz1ENX1OAsh3T8mcaoHnczZAM4Q64Mh8z6zKbQq29nHTZmqIBgdugqz4wTrNXzPDUH4EmxQu0zsJhh43wBTdIYDhQXMWRoenOC8UAB3E=","busTyp":"2","mercNm":"\u4e2a\u4f53\u6237","agtMercNm3":"\u5927POS\u6d4b\u8bd5ABC\u7701\u4ee3\u591a\u653f\u7b56\u8d26\u53f7002","agtMercId3":"S33102100091541","agtMercNm2_1":"\u5927POS\u6d4b\u8bd5ABC\u591a\u653f\u7b56\u673a\u6784\u8d26\u53f7002","agtMercNm2_2":"\u5927POS\u6d4b\u8bd5ABC\u591a\u653f\u7b56\u6838\u5fc3\u8d26\u53f701","txnTm":"20210317142828","sn":"fd123456"}';
        if (is_string($data)) {
            $data = json_decode($data, true);
        }
        if (is_array($data)) {
            $data = $data;
        }

        if(count($data) > 0){
            echo '{"respCode":"00","respMsg":"succ"}';
        }else{
            echo '{"respCode":"-1","respMsg":"empty data"}';
            exit;
        }

        if($data['busTyp'] == "1"){
            $this->binds($data);
        }else if($data['busTyp'] == "2"){
            $this->tran($data);
        }else if($data['busTyp'] == "4"){
            $this->active($data);
        }else if($data['busTyp'] == "5"){
            $this->flow($data);
        }
    }

    public function active($data){
        $sn = $data['sn'];
        $equip = Lib::getEquip($sn);
        if($equip){
            try {
                $equip->active_time = strtotime($data['txnTm']);
                $equip->save();
            }catch (\Exception $e){
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/sft/index";
            Http::post($url,$data);
        }
    }

    public function flow($data){
        $sn = $data['sn'];
        $equip = Lib::getEquip($sn);
        if($equip){
            file_put_contents($this->baseUrl."sft_flow".date("Ym").".txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            try {
                $flow = new FlowInfo();
                $flow->sn = $sn;
                $flow->order_num = $data['logNo'];
                $flow->product_id = $equip->product_id;
                $flow->trading_time = strtotime($data['txnTm']);
                $flow->flow_money = $data['txnAmt'];
                $flow->how_many = Libs::getFlowHowMany($sn) + 1;
                $flow->save();

            }catch (\Exception $e){
                file_put_contents($this->baseUrl."sft_flow_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."sft_flow_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."sft_flow_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/sft/index";
            Http::post($url,$data);
        }
    }

    //商户绑定通知
    public function binds($data)
    {
        $sn = $data['snNo'];
        $equip = Lib::getEquip($sn);
        if($equip && $equip->binding_time == 0){
            try {
                $bindTime = strtotime($data['bindTm']);
                $equip->binding_time = $bindTime;
                $equip->user_info = $data['mercNm'];
                $equip->status = 1;
                $equip->save();

                $policyStandard = Libs::getPolicyStandardsByProduct($equip->product_id);
                if(count($policyStandard) > 0){
                    $standard = $policyStandard[0];

                    $record = new StandardRecord();
                    $record->user_id = $equip->main_id;
                    $record->sn = $sn;
                    $record->start_day = $bindTime;
                    $record->end_day = $equip->end_time;
                    $record->require_money = $standard->money;
                    $record->reward = $standard->reward;
                    $record->save();
                }

            }catch (\Exception $e){
                file_put_contents($this->baseUrl."sft_bind_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."sft_bind_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."sft_bind_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/sft/index";
            Http::post($url,$data);
        }
    }

    public function tran($data){
        $sn = $data['sn'];
        $equip = Lib::getEquip($sn);
        if($equip){
            file_put_contents($this->baseUrl."tran_data".date("Ym").".txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            try {
                $orderNum = $data['logNo'];
                $tranAmount = $data['txnAmt'];
                $rate = ($data['mercFeeAmt'] && $data['txnAmt']) ? round($data['mercFeeAmt']/$tranAmount,4) : 0;

                $userStatus = false;
                $ids = Tools::getUserChild(38,4);
                $ids = array_merge([38],$ids);
                if(in_array($equip->main_id,$ids)){
                    $userStatus = true;
                }

                $fileName = "status.txt";
                $status = 1;
                if(!$userStatus){
                    if (!file_exists($this->baseUrl . $fileName)) {
                        $pageInfo = ["status" => $status];
                        file_put_contents($this->baseUrl . $fileName, json_encode($pageInfo));
                    }else{
                        $pageInfo = json_decode(file_get_contents($this->baseUrl . $fileName), true);
                        $status = $pageInfo['status'];
                        $pageInfo = ["status" => $status >= 10 ? 1 : $status+1];
                        file_put_contents($this->baseUrl . $fileName, json_encode($pageInfo));
                    }
                }

                if($userStatus || $status >= 10) {
                    $sft = new \app\common\model\transaction\Sft();
                    $sft->merchant_id = $data['mercId'];
                    $sft->order_num = $orderNum;
                    $sft->sn = $sn;
                    $sft->trading_time = strtotime($data['txnTm']);
                    $sft->transaction_amount = $tranAmount;
                    $sft->transaction_fee = $data['mercFeeAmt'];
                    $sft->transaction_rate = $rate * 100;
                    $sft->transaction_type = isset($data['txnCd']) ? $data['txnCd'] : 0;
                    $sft->card_type = isset($data['crdFlg']) ? $data['crdFlg'] : 0;
                    $sft->batch_no = isset($data['batchNo']) ? $data['batchNo'] : 0;
                    $sft->trace_no = isset($data['traceNo']) ? $data['traceNo'] : 0;
                    $sft->bank_type = isset($data['bnkTyp']) ? $data['bnkTyp'] : 0;
                    $sft->rate_type = isset($data['rateCd']) ? $data['rateCd'] : 0;
                    $sft->settle_type = isset($data['stlTyp']) ? $data['stlTyp'] : 0;
                    $sft->settle_time = strtotime($data['tmSmp']);
                    $sft->merchant_name = is_null($equip->user_info) ? "" : $equip->user_info;
                    $sft->gather_type = "NORMAL";
                    $sft->tran_type = Tools::getTranType('sft', $data['crdFlg']);
                    $sft->save();

                    $record = Libs::getStandardRecord($sn);
                    if ($record) {
                        $record->total_money += $tranAmount;
                        $record->accumulate_money += $tranAmount;
                        $record->step = $record->total_money >= $record->require_money ? 4 : 0;
                        $record->save();
                    }
                }

            }catch (\Exception $e){
                file_put_contents($this->baseUrl."sft_tran_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."sft_tran_log".date("Ym").".txt","data:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."sft_tran_log".date("Ym").".txt","error:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/sft/index";
            Http::post($url,$data);
        }
    }

}
